package com.yl.rabbitmq.day10;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.yl.rabbitmq.utils.RabbitMQUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yangl
 * 死信队列，设置超出队列最大长度进入死信队列
 */
public class Consumer01 {
    /**
     * 普通交换机的名称
     */
    private static final String NORMAL_EXCHANGE = "normal_exchange02";
    /**
     * 死信交换机的名称
     */
    private static final String DEAD_EXCHANGE = "dead_exchange02";
    /**
     * 普通队列的名称
     */
    private static final String NORMAL_QUEUE = "normal_queue02";
    /**
     * 死信队列的名称
     */
    private static final String DEAD_QUEUE = "dead_queue02";

    public static void main(String[] args) throws Exception{
        Channel channel = RabbitMQUtil.getChannel();
        //声明普通交换机和死信交换机，类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        /**
         * 死信队列
         * 正常队列设置死信交换机
         * 设置死信routingKey
         * 设置队列长度
         */
        Map<String, Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        map.put("x-dead-letter-routing-key", "lisi");
        map.put("x-max-length", 6);
        //声明普通队列
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, map);
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);

        //绑定普通的交换机与队列
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");
        //绑定死信的交换机与队列
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");
        System.out.println("等待接收消息......");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println("consumer01接收的消息是：" + new String(message.getBody(), "UTF-8"));
        };
        channel.basicConsume(NORMAL_QUEUE, true, deliverCallback,consumerTag->{});
    }
}
